<template>
  <view class="page-container">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      :title="isEdit ? '编辑标签' : '创建标签'" 
      :show-back="true"
      @back="handleBack"
      @rightClick="handleSave"
    >
      <template #right>
        <text class="save-btn" :class="{ disabled: !canSave }">{{ saving ? '保存中' : '保存' }}</text>
      </template>
    </CustomNavBar>
    
    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }">
      <scroll-view scroll-y class="content-scroll">
        <!-- 标签预览 -->
        <view class="preview-section">
          <view class="preview-card">
            <view class="preview-tag" :style="{ backgroundColor: formData.color + '20', color: formData.color }">
              <text class="tag-text">{{ formData.name || '标签名称' }}</text>
            </view>
            <text class="preview-desc">这就是你的标签在日记中的显示效果</text>
          </view>
        </view>
        
        <!-- 表单内容 -->
        <view class="form-section">
          <!-- 标签名称 -->
          <view class="form-group">
            <text class="form-label">标签名称 <text class="required">*</text></text>
            <view class="input-wrapper" :class="{ focus: nameFocused }">
              <input
                v-model="formData.name"
                placeholder="请输入标签名称"
                maxlength="10"
                @focus="nameFocused = true"
                @blur="nameFocused = false"
              />
              <text class="input-count">{{ formData.name.length }}/10</text>
            </view>
            <text class="form-hint">标签名称建议简短明了，便于识别和使用</text>
          </view>
          
          <!-- 标签颜色 -->
          <view class="form-group">
            <text class="form-label">标签颜色</text>
            <view class="color-section">
              <view class="current-color">
                <view class="color-preview" :style="{ backgroundColor: formData.color }"></view>
                <text class="color-value">{{ formData.color }}</text>
              </view>
              
              <view class="color-grid">
                <view 
                  class="color-item" 
                  v-for="color in colorOptions" 
                  :key="color"
                  :class="{ active: formData.color === color }"
                  :style="{ backgroundColor: color }"
                  @click="selectColor(color)"
                >
                  <uni-icons v-if="formData.color === color" type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
                </view>
              </view>
              
              <!-- 自定义颜色 -->
              <view class="custom-color">
                <text class="custom-label">自定义颜色</text>
                <input 
                  type="color" 
                  v-model="formData.color"
                  class="color-picker"
                />
              </view>
            </view>
          </view>
          
          <!-- 预设标签 -->
          <view class="form-group" v-if="!isEdit">
            <text class="form-label">常用标签</text>
            <view class="preset-tags">
              <view 
                class="preset-tag" 
                v-for="preset in presetTags" 
                :key="preset.name"
                @click="selectPresetTag(preset)"
              >
                <text class="preset-name">{{ preset.name }}</text>
                <text class="preset-emoji">{{ preset.emoji }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 删除按钮（编辑模式） -->
        <view class="delete-section" v-if="isEdit">
          <button class="delete-btn" @click="handleDelete">
            <uni-icons type="trash" size="18" color="#ff4d4f"></uni-icons>
            <text class="delete-text">删除标签</text>
          </button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 加载组件 -->
    <LoadingComponent :visible="loading || saving" :text="saving ? '保存中...' : '加载中...'" />
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { 
  getTagDetailAPI, 
  createTagAPI, 
  updateTagAPI,
  deleteTagAPI 
} from '@/api/tag'
import { extractResponseData } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'

export default {
  name: 'TagEditPage',
  components: {
    CustomNavBar,
    LoadingComponent
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore
    }
  },
  data() {
    return {
      navBarHeight: 88,
      tagId: null,
      isEdit: false,
      loading: false,
      saving: false,
      nameFocused: false,
      
      formData: {
        name: '',
        color: '#1890ff'
      },
      
      // 颜色选项
      colorOptions: [
        '#1890ff', '#52c41a', '#faad14', '#f5222d',
        '#722ed1', '#eb2f96', '#13c2c2', '#fa541c',
        '#2f54eb', '#a0d911', '#fadb14', '#ff4d4f',
        '#9254de', '#f759ab', '#36cfc9', '#ff7a45',
        '#096dd9', '#389e0d', '#d48806', '#cf1322',
        '#531dab', '#c41d7f', '#08979c', '#d4380d'
      ],
      
      // 预设标签
      presetTags: [
        { name: '工作', color: '#1890ff', emoji: '💼' },
        { name: '学习', color: '#52c41a', emoji: '📚' },
        { name: '生活', color: '#faad14', emoji: '🏠' },
        { name: '旅行', color: '#722ed1', emoji: '✈️' },
        { name: '美食', color: '#eb2f96', emoji: '🍔' },
        { name: '运动', color: '#13c2c2', emoji: '🏃' },
        { name: '电影', color: '#fa541c', emoji: '🎬' },
        { name: '音乐', color: '#2f54eb', emoji: '🎵' },
        { name: '读书', color: '#a0d911', emoji: '📖' },
        { name: '思考', color: '#fadb14', emoji: '💭' },
        { name: '感悟', color: '#ff4d4f', emoji: '💡' },
        { name: '梦想', color: '#9254de', emoji: '🌟' }
      ]
    }
  },
  computed: {
    canSave() {
      return this.formData.name.trim() && !this.saving
    }
  },
  onLoad(options) {
    this.tagId = options.id
    this.isEdit = !!this.tagId
    this.initPage()
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 获取导航栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.navBarHeight = systemInfo.statusBarHeight + 44
      
      // 如果是编辑模式，加载标签详情
      if (this.isEdit) {
        await this.loadTagDetail()
      }
    },
    
    async loadTagDetail() {
      if (!this.tagId) return
      
      this.loading = true
      
      try {
        const res = await getTagDetailAPI(this.tagId)
        const tag = extractResponseData(res)
        
        this.formData = {
          name: tag.name || '',
          color: tag.color || '#1890ff'
        }
        
      } catch (error) {
        console.error('加载标签详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } finally {
        this.loading = false
      }
    },
    
    // 处理返回
    async handleBack() {
      if (this.hasUnsavedChanges()) {
        try {
          await uni.showModal({
            title: '提示',
            content: '有未保存的内容，确定要离开吗？',
            showCancel: true
          })
          uni.navigateBack()
        } catch (error) {
          // 用户取消
        }
      } else {
        uni.navigateBack()
      }
    },
    
    // 检查是否有未保存的更改
    hasUnsavedChanges() {
      return this.formData.name.trim()
    },
    
    // 处理保存
    async handleSave() {
      if (!this.canSave) return
      
      if (!this.validateForm()) return
      
      this.saving = true
      
      try {
        const data = {
          name: this.formData.name.trim(),
          color: this.formData.color
        }
        
        let res
        if (this.isEdit) {
          res = await updateTagAPI(this.tagId, data)
        } else {
          res = await createTagAPI(data)
        }
        
        const tagData = extractResponseData(res)
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 更新状态管理
        if (this.isEdit) {
          this.diaryStore.updateTag(tagData)
        } else {
          this.diaryStore.addTag(tagData)
        }
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.saving = false
      }
    },
    
    // 表单验证
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入标签名称',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.name.trim().length < 1) {
        uni.showToast({
          title: '标签名称不能为空',
          icon: 'none'
        })
        return false
      }
      
      if (this.formData.name.trim().length > 10) {
        uni.showToast({
          title: '标签名称不能超过10个字符',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    // 选择颜色
    selectColor(color) {
      this.formData.color = color
    },
    
    // 选择预设标签
    selectPresetTag(preset) {
      this.formData.name = preset.name
      this.formData.color = preset.color
    },
    
    // 删除标签
    async handleDelete() {
      try {
        await uni.showModal({
          title: '确认删除',
          content: `确定要删除标签"${this.formData.name}"吗？\n删除后该标签将从所有日记中移除。`,
          showCancel: true,
          confirmColor: '#ff4d4f'
        })
        
        this.loading = true
        
        await deleteTagAPI(this.tagId)
        
        // 更新状态管理
        this.diaryStore.deleteTag(this.tagId)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        if (error.errMsg !== 'showModal:fail cancel') {
          console.error('删除标签失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.content-scroll {
  height: calc(100vh - 88px);
  padding-bottom: 120rpx;
}

.preview-section {
  padding: 40rpx 32rpx;
  background-color: #f8f8f8;
}

.preview-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 32rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.preview-tag {
  display: inline-block;
  padding: 12rpx 24rpx;
  border-radius: 20rpx;
  margin-bottom: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.tag-text {
  font-size: 28rpx;
}

.preview-desc {
  font-size: 24rpx;
  color: #666666;
}

.form-section {
  padding: 0 32rpx;
}

.form-group {
  margin-bottom: 40rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 16rpx;
}

.required {
  color: #ff4d4f;
}

.input-wrapper {
  position: relative;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

.input-wrapper.focus {
  background-color: #ffffff;
  border-color: #1890ff;
  box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
}

.input-wrapper input {
  width: 100%;
  padding: 24rpx 80rpx 24rpx 24rpx;
  font-size: 28rpx;
  background-color: transparent;
  border: none;
}

.input-count {
  position: absolute;
  right: 16rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 24rpx;
  color: #999999;
}

.form-hint {
  font-size: 24rpx;
  color: #999999;
  margin-top: 8rpx;
  line-height: 1.4;
}

.color-section {
  margin-top: 16rpx;
}

.current-color {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.color-preview {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  border: 2rpx solid #e5e5e5;
}

.color-value {
  font-size: 28rpx;
  color: #333333;
  font-family: monospace;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 16rpx;
  margin-bottom: 32rpx;
}

.color-item {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

.color-item.active {
  border-color: #333333;
  transform: scale(1.1);
}

.custom-color {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
}

.custom-label {
  font-size: 28rpx;
  color: #333333;
}

.color-picker {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  border: none;
  background-color: transparent;
}

.preset-tags {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;
}

.preset-tag {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx 16rpx;
  background-color: #f8f8f8;
  border-radius: 12rpx;
  border: 2rpx solid transparent;
  transition: all 0.3s;
}

.preset-tag:active {
  background-color: #e6f7ff;
  border-color: #1890ff;
  transform: scale(0.95);
}

.preset-emoji {
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.preset-name {
  font-size: 24rpx;
  color: #333333;
}

.delete-section {
  padding: 0 32rpx 40rpx;
}

.delete-btn {
  width: 100%;
  height: 88rpx;
  background-color: #ffffff;
  border: 2rpx solid #ff4d4f;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16rpx;
  font-size: 28rpx;
  color: #ff4d4f;
}

.delete-btn::after {
  border: none;
}

.delete-text {
  font-size: 28rpx;
  color: #ff4d4f;
}

.save-btn {
  font-size: 28rpx;
  color: #1890ff;
}

.save-btn.disabled {
  color: #cccccc;
}
</style> 